import React, { Component } from 'react';
import { View } from '@tarojs/components';
import { AtTabs, AtTabsPane, AtList, AtLoadMore, AtNavBar } from "taro-ui";
import Taro from '@tarojs/taro';
import "./approve.less";
import config from '../../config.json';
import { Picker } from "antd-mobile";
import { ApproveItem } from '../../modal/component';


interface AgreedData {
    aid: number
    uid: string
    mid: number
    start_time: number
    end_time: number
    reason: string
    note: string
    status: string
    approver: string //审批人
    group?: number
    area: number
    authority: number
    department: string
    mname: string
    uname: string
    wifi: number
}


interface ApproveState {
    datas: AgreedData[],
    wait: AgreedData[],
    pass: AgreedData[],
    timeout: AgreedData[],
    refuse: AgreedData[],
    waitMoreState: "more" | "loading" | "noMore",
    passMoreState: "more" | "loading" | "noMore",
    timeoutMoreState: "more" | "loading" | "noMore",
    refuseMoreState: "more" | "loading" | "noMore",
    statuSelect: string,
    current: number,
    pickerVisible: boolean,
    pickerSelect: string
}

enum pickerEnum {
    "今日起" = "today",
    "一周内" = "week",
    "历史所有" = "history"
}

function tConflict(a: number[], b: number[]): boolean {
    if ((a[1] < b[0]) || (a[0] > b[1])) {
        return true
    } else {
        return false
    }
}

function groupData(datas: AgreedData[]): AgreedData[] {
    let num = 1
    for (let i = 0; i < datas.length; i++) {
        if (i === 0) {
            datas[i].group = num;
            num += 1;
        }
        for (let j = 0; j < i; j++) {
            if (!tConflict([datas[i].start_time, datas[i].end_time], [datas[j].start_time, datas[j].end_time])) {
                datas[i].group = datas[j].group;
            } else if (j === i - 1) {
                datas[i].group = num;
                num += 1;
            }
        }
    }
    datas = datas.sort((a, b) => {
        return a.group - b.group;
    });
    return datas;
}

export default class Approve extends Component<any, ApproveState> {
    constructor(props) {
        super(props);
        this.state = {
            datas: [],
            wait: [],
            pass: [],
            timeout: [],
            refuse: [],
            waitMoreState: "noMore",
            passMoreState: "noMore",
            timeoutMoreState: "noMore",
            refuseMoreState: "noMore",
            statuSelect: "wait",
            current: 0,
            pickerVisible: false,
            pickerSelect: "今日起",
        }
    }

    load(time: string, state: string, offset: number) {
        Taro.showLoading({ title: "加载中..." });
        if (offset === 0) {
            this.setState({
                wait: [],
                pass: [],
                timeout: [],
                refuse: []
            })
        }
        Taro.getStorage({
            key: "token",
            success: (token) => {
                Taro.request({
                    url: config.domainName + "/agreed/query",
                    header: {
                        "token": token.data,
                    },
                    data: {
                        time: pickerEnum[time],
                        state: state,
                        offset: offset
                    },
                    success: (res) => {
                        let response = res.data;
                        if (!response.code) {
                            let data: AgreedData[] = groupData(response.data);

                            this.setState((cstate) => {
                                let temp = cstate;
                                data.forEach((item) => {
                                    temp[state].push(item);
                                });
                                temp[`${state}MoreState`] = data.length === 8 ? "more" : "noMore";
                                return temp;
                            });
                        }
                        Taro.hideLoading();
                    },
                    fail: (res) => {
                        console.log(res);
                        Taro.hideLoading();
                    }
                })
            }
        })
    }

    loadMore(state: string) {
        this.setState((_state) => {
            let temp = _state;
            temp[`${state}MoreState`] = "loading";
            return temp;
        });
        this.load(this.state.pickerSelect, state, this.state[state].length);
    }

    componentWillMount() {
    }

    componentDidMount() {

    }

    componentWillUnmount() { }

    componentDidShow() {
        this.load(this.state.pickerSelect, "pass", 0);
        this.load(this.state.pickerSelect, "wait", 0);
        this.load(this.state.pickerSelect, "timeout", 0);
        this.load(this.state.pickerSelect, "refuse", 0);
    }

    componentDidHide() { }

    handleClick(value) {
        this.setState({
            current: value
        })
    }
    handleClickListItem(data) {
        Taro.setStorageSync("approve_detail", JSON.stringify(data));
        Taro.navigateTo({
            url: '/pages/approvedetail/approvedetail',
        })
    }

    getTime(start: Date, end: Date) {
        return `${start.getFullYear()}年 ${start.getMonth() + 1}月${start.getDate()}日 ${start.getHours() < 10 ? `0${start.getHours()}` : start.getHours()}:${start.getMinutes() < 10 ? `0${start.getMinutes()}` : start.getMinutes()}~${end.getHours() < 10 ? `0${end.getHours()}` : end.getHours()}:${end.getMinutes() < 10 ? `0${end.getMinutes()}` : end.getMinutes()}`;
    }

    render() {
        const tabList = [{ title: '等待中' }, { title: '已通过' }, { title: '已拒绝' }, { title: "已超时" }]
        return (
            <View style={{ marginBottom: "2rem" }}>
                <AtNavBar
                    onClickLeftIcon={() => { Taro.navigateBack() }}
                    color='#000'
                    title='审批列表'
                    leftIconType="chevron-left"
                />
                <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
                    <AtTabsPane current={this.state.current} index={0}>
                        <View className="tab-content">
                            <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: 20 }}>
                                <View className="module-title">申请列表</View>
                                <View
                                    className="primary-color-text-s"
                                    onClick={() => { this.setState({ pickerVisible: true }) }}
                                    style={{
                                        marginRight: "0.6rem",
                                        fontSize: "0.6rem",
                                        cursor: "pointer"
                                    }}
                                >
                                    {this.state.pickerSelect} ▼
                                </View>
                                <Picker
                                    columns={[["今日起", "一周内", "历史所有"]]}
                                    visible={this.state.pickerVisible}
                                    onClose={() => {
                                        this.setState({ pickerVisible: false });
                                    }}
                                    value={[this.state.pickerSelect]}
                                    onConfirm={(value) => {
                                        this.setState({ pickerSelect: value[0] });
                                        this.load(value[0], "pass", 0);
                                        this.load(value[0], "wait", 0);
                                        this.load(value[0], "timeout", 0);
                                        this.load(value[0], "refuse", 0);
                                    }}
                                />
                            </View>
                            {
                                (() => {
                                    return this.state.wait.map((value) => {
                                        if (value.status === "wait") {
                                            return <ApproveItem
                                                onClick={this.handleClickListItem.bind(this, value)}
                                                data={value}
                                            />
                                        }
                                    })
                                })()
                            }
                            <AtLoadMore onClick={this.loadMore.bind(this, "wait")} status={this.state.waitMoreState} />
                        </View>
                    </AtTabsPane>
                    <AtTabsPane current={this.state.current} index={1}>
                        <View className="tab-content">
                            <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: 20 }}>
                                <View className="module-title">通过列表</View>
                                <View
                                    className="primary-color-text-s"
                                    onClick={() => { this.setState({ pickerVisible: true }) }}
                                    style={{
                                        marginRight: "0.6rem",
                                        fontSize: "0.6rem",
                                        cursor: "pointer"
                                    }}
                                >
                                    {this.state.pickerSelect} ▼
                                </View>
                            </View>
                            {
                                (() => {
                                    return this.state.pass.map((value) => {
                                        if (value.status === "pass") {
                                            return <ApproveItem
                                                onClick={this.handleClickListItem.bind(this, value)}
                                                data={value}
                                            />
                                        }
                                    })
                                })()
                            }
                            <AtLoadMore onClick={this.loadMore.bind(this, "pass")} status={this.state.passMoreState} />
                        </View>
                    </AtTabsPane>
                    <AtTabsPane current={this.state.current} index={2}>
                        <View className="tab-content">
                            <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: 20 }}>
                                <View className="module-title">拒绝列表</View>
                                <View
                                    className="primary-color-text-s"
                                    onClick={() => { this.setState({ pickerVisible: true }) }}
                                    style={{
                                        marginRight: "0.6rem",
                                        fontSize: "0.6rem",
                                        cursor: "pointer"
                                    }}
                                >
                                    {this.state.pickerSelect} ▼
                                </View>
                            </View>
                            {
                                (() => {
                                    return this.state.refuse.map((value) => {
                                        if (value.status === "refuse") {
                                            return <ApproveItem
                                                onClick={this.handleClickListItem.bind(this, value)}
                                                data={value}
                                            />
                                        }
                                    })
                                })()
                            }
                            <AtLoadMore onClick={this.loadMore.bind(this, "refuse")} status={this.state.refuseMoreState} />
                        </View>
                    </AtTabsPane>
                    <AtTabsPane current={this.state.current} index={3}>
                        <View className="tab-content">
                            <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: 20 }}>
                                <View className="module-title">超时列表</View>
                                <View
                                    className="primary-color-text-s"
                                    onClick={() => { this.setState({ pickerVisible: true }) }}
                                    style={{
                                        marginRight: "0.6rem",
                                        fontSize: "0.6rem",
                                        cursor: "pointer"
                                    }}
                                >
                                    {this.state.pickerSelect} ▼
                                </View>
                            </View>
                            {
                                (() => {
                                    return this.state.timeout.map((value) => {
                                        if (value.status === "timeout") {
                                            return <ApproveItem
                                                onClick={this.handleClickListItem.bind(this, value)}
                                                data={value}
                                            />
                                        }
                                    })
                                })()
                            }
                            <AtLoadMore onClick={this.loadMore.bind(this, "timeout")} status={this.state.timeoutMoreState} />
                        </View>
                    </AtTabsPane>
                </AtTabs>
            </View>
        )
    }
}
